import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';

// ... 已有导入 ...
interface TabItem {
  key: string;
  label: string;
  path: string;
  closable?: boolean;
  icon?: string | undefined;
}
interface TabState {
  items: TabItem[];
  addTab: (tab: TabItem) => void;
  removeTab: (targetKey: string) => void;
  removeAllTabs: () => void;
  removeOtherTabs: (targetKey: string) => void;
  removeLeftTabs: (index: number) => void;
  removeRightTabs: (index: number) => void;
}

const useTabStore = create<TabState>()(
  devtools(
    persist(
      immer<TabState>((set) => ({
        items: [],
        addTab: (tab) =>
          set((state) => {
            if (!state.items.find((item) => item.key === tab.key)) {
              state.items.push(tab);
            }
          }),
        removeTab: (targetKey) =>
          set((state) => {
            state.items = state.items.filter((item) => item.key !== targetKey);
          }),
        removeAllTabs: () =>
          set((state) => {
            state.items = state.items.filter((item) => item.key === '/Home');
          }),
        removeOtherTabs: (targetKey) =>
          set((state) => {
            state.items = state.items.filter((item) => item.key === targetKey);
          }),
        removeLeftTabs: (index) =>
          set((state) => {
            state.items = state.items.splice(index);
          }),
        removeRightTabs: (index) =>
          set((state) => {
            state.items = state.items.splice(0, index + 1);
          }),
      })),
      { name: 'tabs' },
    ),
  ),
);

export { useTabStore };
